﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using Antu.WebControls;
using Antu.Core.Components;
using Antu.Core.Services;
using System.Web.UI.WebControls;
using System.Web;
using Antu.WorkFlowFactory;
using System.Data;

namespace WebSys.UI.OfficeFlow
{
    public class DelegateRightSkin : MPBasicTemplate
    {
        FlowFactoryProvider _FlowFactoryProvider = (FlowFactoryProvider)ProviderService.ProviderServiceMange.GetProvider("FlowFactoryProvider");
        DropDownList ddlProcessName, ddlUnit, ddlDep, ddlUserName;
        MPCalendar startDate, endDate;
        Button btnUpdate;
        CustomGridView gv;
        protected string UserId
        {
            get { if (base.Page.Session["UserId"] != null) { return base.Page.Session["UserId"].ToString(); } else { return string.Empty; } }
            set { base.Page.Session["UserId"] = value; }
        }
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            InitControl();
            ddlUnit.SelectedIndexChanged += new EventHandler(ddlUnit_SelectedIndexChanged);
            ddlDep.SelectedIndexChanged += new EventHandler(ddlDep_SelectedIndexChanged);
            if (!base.Page.IsPostBack)
            {
                string wnames = System.Configuration.ConfigurationManager.AppSettings["ZSAnJianType"].ToString();
                DataTable dt = _FlowFactoryProvider.GetWnameByUserId(UserId,wnames);
                DataRow dr = dt.NewRow();
                dr["wname"] = "全部";
                dt.Rows.InsertAt(dr, 0);
                ddlProcessName.DataSource = dt;
                ddlProcessName.DataTextField = "wname";
                ddlProcessName.DataValueField = "wname";
                ddlProcessName.DataBind();
                BindData();
                ddlUnit.Items.Add("部门");
                ddlDep.Items.Add("单位");
                ddlUserName.Items.Add("人员");
                BindUnit();
            }
            gv.RowDeleting += new GridViewDeleteEventHandler(gv_RowDeleting);
        }


   

        private void InitControl()
        {
            ddlProcessName = (DropDownList)FindControl("ddlProcessName");
            ddlUnit = (DropDownList)FindControl("ddlUnit");
            ddlDep = (DropDownList)FindControl("ddlDep");
            ddlUserName = (DropDownList)FindControl("ddlUserName");

            startDate = (MPCalendar)FindControl("startDate");
            endDate = (MPCalendar)FindControl("endDate");

            btnUpdate = (Button)FindControl("btnUpdate");
            gv = (CustomGridView)FindControl("gv");
            btnUpdate.Click += new EventHandler(btnUpdate_Click);
        }

        /// <summary>
        /// 绑定表格数据
        /// </summary>
        private void BindData()
        {
            string wnames = System.Configuration.ConfigurationManager.AppSettings["ZSAnJianType"].ToString();
            string sqlwhere=" and delegate_task in("+wnames+")";
            DataTable dt = _FlowFactoryProvider.GetDelegate(UserId,sqlwhere);
            gv.DataSource = dt;
            gv.RecordCount = dt.Rows.Count;
            gv.DataBind();
        }
        private void BindUnit()
        {
            DataTable dt = _FlowFactoryProvider.GetDepartName();
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    ddlUnit.Items.Add(new ListItem(dt.Rows[i][0].ToString(), dt.Rows[i][0].ToString()));
                }

            }
        }
        /// <summary>
        /// 绑定部门数据
        /// </summary>
        private void BindDep(string unitId)
        {
            DataTable dt = _FlowFactoryProvider.GetDepartment(unitId);
            ddlDep.DataSource = dt;
            ddlDep.DataTextField = "depart_name";
            ddlDep.DataValueField = "departid";
            ddlDep.DataBind();
            BindUser(ddlDep.SelectedValue);
        }
        private void BindUser(string depId)
        {
            DataTable dt = _FlowFactoryProvider.GetBindUser(depId);
            ddlUserName.DataSource = dt;
            ddlUserName.DataTextField = "user_name";
            ddlUserName.DataValueField = "userid";
            ddlUserName.DataBind();
        }
        protected void ddlUnit_SelectedIndexChanged(object sender, EventArgs e)
        {
            //加载相应单位下面的部门
            DataTable dt = _FlowFactoryProvider.GetDepartmentByDanWei(ddlUnit.Text.Trim());
            ddlDep.Items.Clear();
            ddlDep.Items.Add("部门");
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    ddlDep.Items.Add(new ListItem(dt.Rows[i][0].ToString(), dt.Rows[i][0].ToString()));
                }
            }
            BindData1();
        }
        protected void ddlDep_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindData1();
        }
        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            string flowtype = ddlProcessName.SelectedValue;
            string date1 = startDate.Text;
            string date2 = endDate.Text;
            if (string.IsNullOrEmpty(date1))
            {
                base.Page.Response.Write("<script>alert('请输入委托开始时间');</script>");
                return;
            }
            if (string.IsNullOrEmpty(date2))
            {
                base.Page.Response.Write("<script>alert('请输入委托结束时间');</script>");
                return;
            }
            if (!string.IsNullOrEmpty(date1) && !string.IsNullOrEmpty(date2))
            {
                DateTime d1 = Convert.ToDateTime(date1);
                DateTime d2 = Convert.ToDateTime(date2);
                if (d1 >= d2)
                {
                    base.Page.Response.Write("<script>alert('委托开始时间不能大于或等于委托结束时间');</script>");
                    return;
                }
            }
            if (_FlowFactoryProvider.CheckDelegateByUserId(UserId, flowtype))
            {
                _FlowFactoryProvider.InsertNewDelegate(UserId, ddlUserName.SelectedValue, ddlProcessName.SelectedValue, startDate.Text, endDate.Text);
                BindData();
            }
            else
            {
                base.Page.Response.Write("<script>alert('如果要新增委托请删除旧的委托');</script>");
            }

        }
        protected void gv_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            LinkButton lb = (LinkButton)gv.Rows[e.RowIndex].FindControl("ImageButton1");
            string id = lb.CommandArgument;
            _FlowFactoryProvider.DeleteTableRow("ST_Delegate", "ID", id);
            BindData();
        }

        protected void BindData1()
        {
            string dwName = ddlUnit.Text.Trim();
            string bmName = ddlDep.Text.Trim();
            string strSql = string.Empty;
            if (!string.IsNullOrEmpty(dwName) && dwName != "单位")
            {
                strSql = " SELECT distinct m.* FROM st_user m , st_user_department n, st_department k WHERE m.userid = n.userid and n.order_id = k.departid";
                string result0 = string.Empty;
                string strSql0 = string.Format("select count(*)  from st_department h where h.parent_id in (select h.departid  from st_department h where h.depart_name='" + dwName + "'  and h.parent_id='0')");
                result0 = _FlowFactoryProvider.GetSomeStr("(" + strSql0 + ")", "*", "");
                if (result0 == "0")
                {
                    strSql += " and k.depart_name = '" + dwName + "'";
                }
                else
                {
                    if (!string.IsNullOrEmpty(bmName) && bmName != "部门")
                    {
                        strSql += " and k.depart_name like '%" + bmName + "%'   and k.departid in (select j.departid  from st_department j  where j.parent_id in  (select h.departid from st_department h where h.depart_name = '" + dwName + "'))";
                    }
                    else
                    {
                        strSql += "  and k.departid in (select j.departid  from st_department j  where j.parent_id in  (select h.departid from st_department h where h.depart_name = '" + dwName + "'))";
                    }
                }
                strSql += " order by orderbyid asc";
            }
            else
            {
                strSql = @"select m.* from ST_USER m where 1=1";
            }
            DataTable dt = _FlowFactoryProvider.DoDataTableSql(strSql);
            DataRow dr = dt.NewRow();
            dr["user_name"] = "人员";
            dt.Rows.InsertAt(dr, 0);
            ddlUserName.DataSource = dt;
            ddlUserName.DataTextField = "user_name";
            ddlUserName.DataValueField = "userid";
            ddlUserName.DataBind();
        }
    }
}


